package cn.xq.pethome.dept.service.impl;

import cn.xq.pethome.base.service.impl.BaseServiceImpl;
import cn.xq.pethome.dept.domain.Department;
import cn.xq.pethome.dept.mapper.DepartmentMapper;
import cn.xq.pethome.dept.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceimpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Transactional
    @Override
    public void update(Department department) {
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void insert(Department department) {
        if (department.getParent_id()==null){
            departmentMapper.insert(department);
            Long id = department.getId();
            department.setDirPath("/"+id);
            departmentMapper.update(department);
        }else{
            departmentMapper.insert(department);
            Long parent_id = department.getParent_id();
            Department fingone = departmentMapper.fingone(parent_id);
            String dirPath = fingone.getDirPath();
            department.setDirPath(dirPath+"/"+ department.getId());
            departmentMapper.update(department);
        }

    }

    @Transactional
    @Override
    public void delete(Long id) {
        Long byParentId = departmentMapper.findByParentId(id);
            if(byParentId==0){
                departmentMapper.delete(id);
            }else {
                throw new RuntimeException("部门存在下级，不能删除！");
            }
    }



    @Override
    public Department fingone(Long id) {
        return departmentMapper.fingone(id);
    }

    @Override
    public List<Department> fingall() {
        return departmentMapper.fingall();
    }


    @Transactional
    @Override
    public void batchDelete(List ids) {
        departmentMapper.batchDelete(ids);
    }

    @Override
    public List<Department> departmentTree() {
        List<Department> fingall = departmentMapper.fingall();
        List<Department> parentTree = new ArrayList<>();
        for (Department department : fingall) {
            if(department.getParent_id()==null){
                parentTree.add(department);
            }else {
                for (Department department11 : fingall) {
                    if (department.getParent_id()==department11.getId()){
                        department11.getChildren().add(department);
                    }
                }
            }
        }
        return parentTree;
    }


}
